package cn.ly.queue;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.concurrent.PriorityBlockingQueue;

import cn.ly.util.ArithmeticTool;
import org.junit.Test;

public class QueueApp implements Runnable{
	
	private PriorityBlockingQueue<String> pbq;
	
	public QueueApp(PriorityBlockingQueue<String> pbq){
		this.pbq = pbq;
	}
	
	public QueueApp(){
		
	}

	public void run() {
		String str = "";
		while(!str.equals("bye")){
			try {
				str = this.pbq.take();
				System.out.println("Thread read pbq :" + str);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		System.out.println("===run last===");
	}
	

	public void testQueue(){
		/*Queue myq = new Queue(5);
		for(int i=0; i < 4; i++){
			myq.insert(ArithmeticTool.getIntRandom0to100());
		}
		System.out.println(myq.peek());
		for(int i=0; i<3; i++){
			System.out.println( myq.remove());
		}
		int j = myq.size()-myq.getItems();
		for(int i=0; i < j;i++){
			myq.insert(ArithmeticTool.getIntRandom0to100()+"str");
		}
		System.out.println(myq.isFull());*/
	}

	@Test
	public void testPriorQueue(){
		PriorQueue myq = new PriorQueue(5);
		for(int i=0; i < 4; i++){
			myq.insert(ArithmeticTool.getIntRandom0to100());
		}
		
		for(int i=0; i<2; i++){
			System.out.println( myq.remove());
		}
		System.out.println("=====================================" + myq.getItems());
		for(int i=0; !myq.isFull();i++){
			myq.insert(ArithmeticTool.getIntRandom0to100());
		}
		for(int i=0; !myq.isEmpty();i++){
			System.out.println(myq.remove());
		}
	}

	public void PriorityQueueJDK(){
		PriorityQueue<Integer> pq = new PriorityQueue<Integer>(10);
		for(int i=0;i<5;i++){
			pq.offer(ArithmeticTool.getIntRandom0to100());
		}
		pq.add(81);
		int peek = pq.peek();
		System.out.println("peek : "+peek);
		System.out.println("########################################");
		Iterator it = pq.iterator();//无序的
		while(it.hasNext()){
			System.out.println(it.next());
		}
		System.out.println("########################################");
		System.out.println("size : "+pq.size());
		
		System.out.println("========================================");
		while(pq.size() > 0){
			System.out.println(pq.remove());//删除得到的数据是有序的
		}
	}

	public void testBlockQueue() throws IOException{
		PriorityBlockingQueue<String> pbq = new PriorityBlockingQueue<String>();
		Thread t1 = new Thread(new QueueApp(pbq));
		t1.start();
		InputStreamReader isr = new InputStreamReader(System.in);
		BufferedReader reader = new BufferedReader(isr);
		String line = null;
		System.out.println("input :");
		while( (line = reader.readLine()) != null){
			pbq.add(line);
			if(line.indexOf("bye") > -1){
				break;
			}
		}
	}
	
	
	public static void main(String[] args) throws IOException {
		new QueueApp().testBlockQueue();
	}

}
